<template>
  <div class="app-container">
    <!-- <div class="d-flex justify-space-between align-center">
      <span>{{ pageType === 'add' ? '新增岗位' : '编辑岗位' }}</span>
      <el-button type="primary" plain @click="$router.go(-1)">返回</el-button>
    </div> -->
    <el-form ref="form" :rules="rules" :model="form" label-width="130px" style="width: 450px">
      <el-form-item label="岗位名称：" prop="name">
        <el-input v-model="form.name" clearable placeholder="请输入团队名称" />
      </el-form-item>
      <el-form-item label="角色：" prop="type">
        <el-select v-model="form.type" style="width: 320px" clearable placeholder="请选择" :disabled="pageType !== 'add'">
          <el-option v-for="item in jobList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="岗位类型：">
        <el-select v-model="form.channelId" style="width: 320px" clearable placeholder="请选择岗位">
          <el-option label="前端" value="1" />
          <el-option label="后端" value="2" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="渠道："  v-if="form.type === 4">
          <el-select
            v-model="form.channelId"
            style="width: 320px"
            clearable
            placeholder="请选择岗位"
          >
            <el-option
              v-for="item in channelList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
      <el-form-item label="岗位权限：" prop="permissionIdList">
        <el-tree ref="tree" :data="treeData" show-checkbox node-key="id" :check-strictly="true" :default-checked-keys="form.permissionIdList" :props="{
              children: 'childList',
              label: 'name'
            }" @check-change="handleCheckChange" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSave">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { addRole, updateRole } from "@/api/role";
import { getPermissions } from "@/api/user";
import { jobList } from "./const";
import { getAllChannelList } from "@/api/channel/index";
import {broadcast} from '@/utils/util'
export default {
  name: "PostCreate",
  props: {
    status: {
      type: String,
      default: "add",
    },
    info: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      form: {
        id: "",
        name: "",
        type: "",
        permissionIdList: [],
        // channelId: ''
      },
      jobList,
      treeData: [],
      rules: {
        name: [{ required: true, message: "请输入岗位名称", trigger: "blur" }],
        type: [
          { required: true, message: "请选择角色", trigger: "change" },
        ],
        permissionIdList: [
          {
            type: "array",
            required: true,
            message: "请勾选岗位权限",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    pageType() {
      return this.status;
    },
  },
  created() {
    this.getPermissions();
    // this.getAllChannelList()
    if (this.pageType !== "add") {
      const row = this.info;
      Object.keys(this.form).forEach((key) => {
        if (key === "permissionIdList") {
          this.form["permissionIdList"] = this.flattenTree(row?.permissions);
        } else {
          this.form[key] = row[key];
        }
      });
    }
  },
  methods: {
    async getAllChannelList() {
      const res = await getAllChannelList();
      if (!res.result) return;
      this.channelList = res.data.map((item) => {
        return {
          value: item.id,
          label: item.nickname,
        };
      });
    },
    async getPermissions() {
      const res = await getPermissions();
      if (!res.result) return;
      this.treeData = res.data || [];
    },
    handleCheckChange(a, b, c) {
      console.log(a);
      this.form.permissionIdList = this.$refs.tree
        .getCheckedNodes()
        .map(({ id }) => id);
      // this.form.permissionIdList = this.$refs.tree.getCheckedNodes(false, true).map(({ id }) => id)
      // console.log(this.form.permissionIdList)
      // console.log(2, this.$refs.tree.getCheckedNodes(false, true).map(({ id }) => id))
    },
    flattenTree(list) {
      if (!list) return [];
      let tempList = [];
      list.forEach((item) => {
        tempList.push(item);
        if (item.childList.length > 0) {
          tempList = [...item.childList, ...tempList];
        }
      });
      return tempList.map(({ id }) => id);
    },
    async onSave() {
      try {
        await this.$refs["form"].validate();
        this.pageType === "add" ? this.addRole() : this.updateRole();
      } catch (error) {}
    },
    async addRole() {
      const { code } = await addRole(this.form);
      if (code === 200) {
        this.$message.success("新增岗位成功");
        //this.$router.go(-1);
        broadcast('close.user.post')
        broadcast('post.add.succes')
      }
    },
    async updateRole() {
      const { code } = await updateRole(this.form);
      if (code === 200) {
        this.$message.success("编辑岗位成功");
        //this.$router.go(-1);
        broadcast('close.user.post')
        broadcast('post.add.succes')
      }
    },
  },
};
</script>
